package fun._6742.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun._6742.exception.CustomException;
import fun._6742.mapper.BannerMapper;
import fun._6742.model.dataobject.BannerDO;
import fun._6742.model.valueobject.BannerVO;
import fun._6742.request.CreateBannerRequest;
import fun._6742.service.AdminBannerService;
import fun._6742.utils.ImageUtils;
import fun._6742.utils.oss.MinioTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminBannerServiceImpl extends ServiceImpl<BannerMapper, BannerDO> implements AdminBannerService {


    @Override
    public void createBanner(CreateBannerRequest createBannerRequest) {
        if (createBannerRequest.getImg().isBlank()) {
            throw new CustomException(HttpStatus.NOT_FOUND, "product CoverImg is null");
        }

        BannerDO bannerDO = new BannerDO(createBannerRequest);

        boolean res = save(bannerDO);
        if (!res) {
            log.info("res: false,insert failed:{}", bannerDO);
            throw new CustomException(HttpStatus.NOT_FOUND, "create banner error");
        }
        log.info("res: true,insert success:{}", bannerDO);
    }

    @Override
    public void deleteBanner(long id) {
        if (!removeById(id)) {
            log.error("deleteBanner:res:false,id:{}", id);
            throw new CustomException(HttpStatus.NOT_FOUND, "Banner(id=" + id + " does not exist");
        }
        log.info("deleteBanner:res:true,id:{}", id);
    }

    @Override
    public Object findOne(long bannerId) {

        BannerDO bannerDO = getById(bannerId);
        if (bannerDO == null) {
            log.error("findBanner:res:false,id:{}", bannerId);
            throw new CustomException(HttpStatus.NOT_FOUND, "banner(id=" + bannerId + " does not exist");
        }
        BannerVO bannerVO = new BannerVO();
        BeanUtil.copyProperties(bannerDO, bannerVO);
        return bannerVO;
    }

    @Override
    public Object findPage(int page, int size) {

        IPage<BannerDO> bannerDOIPage = page(new Page<>(page, size));
        Map<String, Object> map = new HashMap<>(3);
        map.put("total_page", bannerDOIPage.getPages());
        map.put("total_record", bannerDOIPage.getTotal());
        map.put("data", bannerDOIPage.getRecords().stream().map(obj -> {
            BannerVO bannerVO = new BannerVO();
            BeanUtil.copyProperties(obj, bannerVO);
            return bannerVO;
        }).collect(Collectors.toList()));
        return map;
    }
}
